<?php

namespace App\Kuafu\Common\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use Kuafu\Recognizer\IDCardRecognizer;
use Kuafu\Recognizer\RecognizeAllText;
use OSS\Core\OssException;

class OcrService
{

    protected string $file;
    protected string $fileType;

    /**
     * @throws GuzzleException
     */
    public function __construct(string $filePath, string $fileType)
    {
        $this->fileType = $fileType;

        switch ($fileType) {
            case 'oss':
                $png = sys_get_temp_dir() . '/' . Str::random() . '.png';

                if (strpos($filePath, FileUtil::domain()) !== false) {
                    $url = $filePath;
                } else {
                    $url = FileUtil::domain() . '/' . $filePath;
                }

                // 下载文件
                (new Client())->get($url, [
                    'sink' => $png,
                ]);

                $this->file = $png;
                break;
            case 'url':
                $png = sys_get_temp_dir() . '/' . Str::random() . '.png';

                // 下载文件
                (new Client())->get($filePath, [
                    'sink' => $png,
                ]);

                $this->file = $png;
                break;
            case 'location':
                $this->file = $filePath;
                break;
            default:
                // 其他类型直接处理
                $this->file = $filePath;
        }
    }


    /**
     * 正面照片识别
     */
    public function idCardFaceOcr(): array
    {
        return Cache::remember($this->getFileMd5() . '_face', 86400 * 30, function () {
            $zer = new IDCardRecognizer($this->file, 'face');
            $res = $zer->recognize();
            $zer = null;// __destruct() 方法自动删掉oss文件
            $this->delLocationFile();
            return $res['Data']['FrontResult'];
        });
    }

    /**
     * 国徽面识别
     */
    public function idCardBackOcr(): array
    {
        return Cache::remember($this->getFileMd5() . '_back', 86400 * 30, function () {
            $zer = new IDCardRecognizer($this->file, 'back');
            $res = $zer->recognize();
            $zer = null; // __destruct() 方法自动删掉oss文件
            $this->delLocationFile();
            return $res['Data']['BackResult'];
        });
    }

    /**
     * 通用文字识别
     */
    public function allTextOcr(): array
    {
        return Cache::remember($this->getFileMd5() . '_allText', 86400 * 30, function () {
            $zer = new RecognizeAllText($this->file);
            $res = $zer->recognize();
            $zer = null; // __destruct() 方法自动删掉oss文件
            $this->delLocationFile();

            // 识别到的所有内容
            $contentArr = [];
            foreach (($res['Data']['Results'] ?? []) as $item) {
                $contentArr[] = $item['Text'];
            }

            return $contentArr;
        });
    }

    /**
     * 删除临时文件
     * @return void
     */
    public function delLocationFile()
    {
        if ($this->fileType == 'location') {
            @unlink($this->file);
        }
    }

    /**
     * 获得文件的 md5
     * @return string
     */
    public function getFileMd5(): string
    {
        // 获得文件的md5值
        $content = file_get_contents($this->file);
        return 'image_orc_' . md5($content);
    }
}